import { Record, List, Map } from 'immutable';
import generateId from '../../utils/generate-id';

const DEFAULTS = {
  id: undefined,
  name: undefined,
  fields: List()
};

function createField(attr = {}) {
  const { name, typeId } = attr;
  return new Map({ name, typeId });
}

function createFieldList(attr = []) {
  if (Array.isArray(attr) || List.isList(attr)) {
    return List(attr.map(createField));
  }
}

class CompositeType extends Record(DEFAULTS) {
  static isCompositeType(object) {
    return !!object.__dataType__;
  }

  static create(attr = {}) {
    if (CompositeType.isCompositeType(attr)) {
      return attr;
    }
    const { name, fields = [], id = generateId() } = attr;
    return new CompositeType({ name, fields: createFieldList(fields), id });
  }
}

CompositeType.prototype.__dataType__ = true;
export default CompositeType;
